package com.zyg.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyg.entity.Student;
import com.zyg.entity.vo.StudentVo;
import com.zyg.mapper.ClassesMapper;
import com.zyg.mapper.StudentMapper;
import com.zyg.service.StudentService;
import lombok.val;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public List<Student> findAll() {
        //1.得到所有学生
        List<Student> students = studentMapper.selectList(null);
        //1.2为学生设置关联的班级
        for (Student student : students) {
            student.setCname(classesMapper.selectById(student.getCid()).getCname());
        }
        //1.3返回学生列表
        return students;
    }

    @Override
    public int delete(int sid) {
        return studentMapper.deleteById(sid);
    }

    @Override
    public int update(Student student) {
        return studentMapper.updateById(student);
    }

    @Override
    public Student findById(int sid) {
        Student student =  studentMapper.selectById(sid);
        student.setSname(classesMapper.selectById(student.getCid()).getCname());
        return student;
    }

    @Override
    public int add(Student student) {
        return studentMapper.insert(student);
    }

    @Override
    public IPage<Student> findByPage(int page, int pageSize) {
        //封装查询参数
        IPage<Student> ipage = new Page<>(page,pageSize);
        //封装查询条件
        Wrapper<Student> wrapper = new QueryWrapper<>();
        //开始分页并放回
        return studentMapper.selectPage(ipage, wrapper);  //参数1：代表分页参数对象 参数2：代表条件查询对象
    }

    @Override
    public IPage<Student> search(int page, int pageSize, StudentVo vo) {
        //封装查询参数
        IPage<Student> ipage = new Page<>(page,pageSize);
        //封装查询条件
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        //开始分页并放回
        if (vo != null){
            if (StringUtils.isEmpty(vo.getName())){
                wrapper.like("sname",vo.getName());
            }
            if (StringUtils.isEmpty(vo.getAddr())){
                wrapper.like("addr",vo.getAddr());
            }
            if (vo.getCid() != null){
                wrapper.like("cid",vo.getCid());
            }
        }
        return studentMapper.selectPage(ipage, wrapper);
    }
}
